package com.exit66.jukebox.servlet.xml;

import javax.servlet.http.HttpServletRequest;

import com.exit66.jukebox.Options;
import com.exit66.jukebox.data.Album;
import com.exit66.jukebox.data.AlbumCollection;
import com.exit66.jukebox.util.XmlSegment;

public class AlbumListServlet extends XmlResponseServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = -3209110559333659974L;

	protected void buildXml(HttpServletRequest req, XmlSegment xml) {
        AlbumCollection list = new AlbumCollection();
        Album album = null;
        
		String[] params;
		if (req.getPathInfo() != null)
			params = req.getPathInfo().split("/");
		else
			params = new String[0];
		
        try {
            int start = 0;
            int count = 0;
            
            if (req.getParameter("start") != null) 
            	start = Integer.parseInt(req.getParameter("start"));
            if (req.getParameter("count") != null) 
            	count = Integer.parseInt(req.getParameter("count"));
            
        	if (params.length > 0) {
	        	if (params[1].equals("artist")) {
	        		list.listByArtist(Integer.parseInt(params[2]), start, count);
	            } else if (Options.isInteger(params[1])) { 
	                album = new Album();
	                album.setAlbumID(new Integer(params[1]).intValue());
	                album.fetch();
	
	                xml.appendSegment(album.returnXml(true, false, false, false));
	                return;
	            }
        	} else {
                list.list(start, count);
            }
            
            while (!list.isEOF()) {
                album = (Album)list.getCurrent();
                xml.appendSegment(album.returnXml(true, false, false, false));
                list.moveNext();
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
